/*
 * @Author: 郑俊标
 * @Date: 2024-06-08 15:41:26
 * @LastEditors: 郑俊标
 * @LastEditTime: 2024-07-12 15:05:08
 * @Description: 
 */
import auth from '@/plugins/auth';
import Layout from '@/layout/index';
import ParentView from '@/components/ParentView';
import InnerLink from '@/layout/components/InnerLink';
import { getRouters } from "@/api/menu";
import router, { constantRoutes, dynamicRoutes } from '@/router';

const permission = {
    state: {
		routes: [],
		addRoutes: [],
		defaultRoutes: [],
		topbarRouters: [],
		sidebarRouters: [],
	},
	mutations: {
		SET_ROUTES: (state, routes) => {
			state.addRoutes = routes;
			state.routes = constantRoutes.concat(routes);
		},
		SET_DEFAULT_ROUTES: (state, routes) => {
			state.defaultRoutes = constantRoutes.concat(routes);
		},
		SET_TOPBAR_ROUTES: (state, routes) => {
			state.topbarRouters = routes;
		},
		SET_SIDEBAR_ROUTERS: (state, routes) => {
			state.sidebarRouters = routes;
		},
	},
    actions: {
        GenerateRoutes({ commit }) {
            return new Promise((resolve, reject) => {
                getRouters().then(res => {
                    const sdata = JSON.parse(JSON.stringify(res.data));
                    const rdata = JSON.parse(JSON.stringify(res.data));
                    // 侧边栏路由
                    const sidebarRoutes = filterAsyncRouter(sdata);
                    const rewriteRoutes = filterAsyncRouter(rdata, false, true);
                    const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
                    rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true });
                    router.addRoutes(asyncRoutes);
                    commit('SET_ROUTES', rewriteRoutes);
                    // 侧边总路由，常态 + 动态路由
                    commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes));
                    // 默认路由
                    commit('SET_DEFAULT_ROUTES', sidebarRoutes);
                    // 顶部路由
					commit('SET_TOPBAR_ROUTES', sidebarRoutes);
					resolve(rewriteRoutes);
                })
            })
        }
    }        
}

// 遍历后台传来的路由字符串，转换为路由对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
    // type 用于控制是否处理子路由（默认为 false）。
    // lastRouter 用于标记上一级路由（默认为 false）
    return asyncRouterMap.filter((route) => {
        if (type && route.children) {
            // 处理子路由
            route.children = filterChildren(route.children);
        }
        // 处理路由组件 替换成真正的系统组件
        if (route.component === 'Layout') {
            route.component = Layout;
        } else if (route.component === 'ParentView') {
            route.component = ParentView;
        } else if (route.component === 'InnerLink') {
            route.component = InnerLink;
        } else {
            // 懒加载自身组件
            route.component = loadView(route.component);
        }
        // 如果存在子路由，则继续递归替换
        if (route.children !== null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children, route, type);
        } else {
            delete route['children'];
            delete route['redirect']
        }
        return true;
    })

}

// 处理子路由，把嵌套的子路由组成一起，拍平【它递归地遍历路由树，并将其平展成一个单层数组】
// lastRouter 是否是真的可以点击的父级路由
function filterChildren(childrenMap, lastRouter = false) {
    var children = [];
    childrenMap.forEach((el) => {
        if (el.children && el.children.length) {
            if (el.component === 'ParentView' && !lastRouter) {
                el.children.forEach((c) => {
                    // 设置这层的path
                    c.path = el.path + '/' + c.path;
                    if (c.children && c.children.length) {
                        children = children.concat(c.children, c);
                        return;
                    };
                    children.push(c);
                });
                return;
            }
        }
        if (lastRouter) {
            el.path = lastRouter.path + '/' + el.path;
            if (el.children && el.children.length) {
                children = children.concat(filterChildren(el.children, el));
                return;
            }
        }
        // 只有一级子路由
        children = children.concat(el);
    });
    return children;
}

// 动态加载组件
export const loadView = (view) => {
    if (process.env.NODE_ENV === 'development') {
        return (resolve) => require([`@/views/${view}`], resolve);
    } else {
        // 生产环境动态加载组件
        return () => import(`@/views/${view}`);
    }
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
    const res = [];
    routes.forEach((route) => {
        // 权限
        if (route.permissions) {
            if (auth.hasPermiOr(route.permissions)) {
                res.push(route);
            }
        } else if (route.roles) {
            if (auth.hasRoleOr(route.roles)) {
                res.push(route);
            }
        }
    });
    return res;
}
export default permission;